﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Messaging.Events;
using Orchard.ContentManagement;
using Orchard.Messaging.Models;
using Orchard.Environment.Extensions;

namespace FruitCake.ContactPage.Handlers
{
    [OrchardFeature("FruitCake.ContactPage")]
    public class ContactPageMessageAlteration : IMessageEventHandler
    {
        public void Sending(MessageContext context)
        {
            if (context.Type == "ContactPage")
            {
                Dictionary<string, string> props = context.Properties;
                System.Net.Mail.MailMessage msg = context.MailMessage;

                msg.ReplyToList.Add(new System.Net.Mail.MailAddress((string)context.Properties["Mail"], (string)context.Properties["Name"]));

                AddAddress(msg.CC, props, "CcList");
                AddAddress(msg.Bcc, props, "BccList");

                msg.Subject = props["MailSubject"];
                msg.IsBodyHtml = false;
                msg.Body = props["MailBody"];                
            }
        }

        private void AddAddress(
            System.Net.Mail.MailAddressCollection addresses,
            Dictionary<string, string> props,
            string key)
        {
            if (!props.ContainsKey("CcList")) return;
            string value = props["CcList"];
            if (string.IsNullOrWhiteSpace(value)) return;
            addresses.Add(value);
        }

        public void Sent(MessageContext context)
        {
        }
    }
}